package com.mdp.workflow.ru.ctrl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.core.entity.LangTips;
import com.mdp.core.entity.Result;
import com.mdp.core.err.BizException;
import com.mdp.core.query.QueryTools;
import com.mdp.core.utils.RequestUtils;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.swagger.ApiEntityParams;
import com.mdp.workflow.api.ExecutionService;
import com.mdp.workflow.ru.entity.Execution;
import com.mdp.workflow.ru.entity.ProcinstParames;
import com.mdp.workflow.ru.service.ExecutionServiceImpl;
import com.mdp.workflow.ru.vo.ProcStartVo;
import com.mdp.workflow.ru.service.ProcinstParamesService;
import com.mdp.workflow.ru.service.ProcinstTagService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value="/**/ru/execution")
@Api(tags={"act_ru_execution-操作接口"})
public class ExecutionController {
	
	static Logger logger =LoggerFactory.getLogger(ExecutionController.class);
	
	@Autowired
	private ExecutionServiceImpl executionService;

	@Autowired
	private ProcinstTagService procinstTagService;

	@Autowired
	private ProcinstParamesService procinstParamesService;

	@Value(value = "${mdp.platform-branch-id:platform-branch-001}")
	String platformBranchId;

	@ApiOperation( value = "act_ru_execution-查询列表",notes=" ")
	@ApiEntityParams(Execution.class)
	@ApiResponses({
		@ApiResponse(code = 200,response=Execution.class,message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")
	})
	@RequestMapping(value="/list",method=RequestMethod.GET)
	public Result listExecution(@ApiIgnore @RequestParam Map<String,Object> params){
		try {
			User user=LoginUtils.getCurrentUserInfo();
			params.remove("tenantId");
			RequestUtils.transformArray(params, "categoryIds");
			RequestUtils.transformArray(params, "tagIds");
			RequestUtils.transformArray(params, "procInstIds");
			QueryWrapper<Execution> qw = QueryTools.initQueryWrapper(Execution.class , params,"res.*","pa.*","p.*").in("res.tenant_id_",platformBranchId,user.getBranchId());
			IPage page=QueryTools.initPage(params);
			List<Map<String,Object>> datas = executionService.selectListMapByWhere(page,qw,params);
			return Result.ok("query-ok","查询成功").setData(datas).setTotal(page.getTotal());
		}catch (BizException e) {
			return Result.error(e);
		}catch (Exception e) {
			return Result.error(e);
		}
	}


	@RequestMapping(value="/start")
	public Result start(@RequestBody ProcStartVo procStartVo) {
		Result result=executionService.start(procStartVo);
		Result.assertIsFalse(result.getTips());
		ProcinstParames ps=procStartVo.getProcinstParames();
		String tagIds=ps.getTagIds();
		String tagNames=ps.getTagNames();
		this.procinstTagService.batchInsertTags(tagIds,tagNames,ps.getBranchId(),ps.getUserid(),ps.getProcDefId(),ps.getProcInstId());
		return Result.ok().setData(procStartVo);
	}

	@RequestMapping(value="/activite")
	public Result activate(@RequestBody com.mdp.workflow.ru.entity.Execution excution) {

		try{
			return executionService.activateProcessInstance(excution.getProcInstId());
		}catch (BizException e) {
			logger.error("执行异常",e);
			return Result.error(e);
		}catch (Exception e) {
			logger.error("执行异常",e);
			return Result.error(e.getMessage());
		}
	}

	@RequestMapping(value="/suspend")
	public Result suspend(@RequestBody com.mdp.workflow.ru.entity.Execution excution) {
		return executionService.suspendProcessInstance(excution.getProcInstId());
	}
	@ApiOperation( value = "act_ru_execution-删除",notes=" ")
	@ApiResponses({
		@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}}")
	}) 
	@RequestMapping(value="/del",method=RequestMethod.POST)
	public Result delExecution(@RequestBody Execution execution){
		User user=LoginUtils.getCurrentUserInfo();
		String modelBranchId=execution.getTenantId();
		if(StringUtils.isEmpty(modelBranchId)) {
			return Result.error("请上送机构号tenantId");
		} else if(!user.getBranchId().equals(modelBranchId)){
			return Result.error("tenant-id-not-platform-001","tenantId","该流程属于其它机构的流程模型，或者属于公共平台共享模型，你无权删除");
		}
			ProcinstParames procinstParames=new ProcinstParames();
			procinstParames.setProcInstId(execution.getProcInstId());
			List<ProcinstParames> plist=procinstParamesService.selectListByWhere(procinstParames);
			ProcinstParames procinstParamesDb=null;
			Map<String,Object> localVars=new HashMap<>();
			if(plist!=null && plist.size()>0) {
				procinstParamesDb=plist.get(0);
				localVars=executionService.localVarsHandle(procinstParamesDb, null, null, localVars);
			}
			if(user.getUserid().equals(execution.getStartUserId())) {
				executionService.delExecution(execution.getProcInstId(), user.getUsername()+"删除流程", localVars);
			} else if( LoginUtils.hasAnyRoles("flowAdmin","platformAdmin","branchAdmin")) {
				executionService.delExecution(execution.getProcInstId(), user.getUsername()+"删除流程", localVars);
			}else{
				return Result.error("need-flowAdmin-or-platformAdmin","roles","该接口属于重大影响接口，需要流程发起人/流程管理员/机构管理员/平台管理员才能操作");
			};
        return Result.ok("del-ok","删除成功！");
	}

	@ApiOperation( value = "act_ru_execution-修改",notes=" ")
	@ApiResponses({
		@ApiResponse(code = 200,response=Execution.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")
	}) 
	@RequestMapping(value="/edit",method=RequestMethod.POST)
	public Result editExecution(@RequestBody Execution execution) {
		executionService.updateById(execution);
        return Result.ok("edit-ok","修改成功！");
	}

    @ApiOperation( value = "act_ru_execution-批量修改某些字段",notes="")
    @ApiEntityParams( value = Execution.class, props={ }, remark = "act_ru_execution", paramType = "body" )
	@ApiResponses({
			@ApiResponse(code = 200,response=Execution.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")
	})
	@RequestMapping(value="/editSomeFields",method=RequestMethod.POST)
	public Result editSomeFields( @ApiIgnore @RequestBody Map<String,Object> params) {
        try{
            User user= LoginUtils.getCurrentUserInfo();
            executionService.editSomeFields(params);
            return Result.ok("edit-ok","更新成功");
        }catch (BizException e) {
            logger.error("",e);
            return Result.error(e);
        }catch (Exception e) {
            logger.error("",e);
            return Result.error(e);
        }
	}

	@ApiOperation( value = "act_ru_execution-批量删除",notes=" ")
	@ApiResponses({
		@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}")
	}) 
	@RequestMapping(value="/batchDel",method=RequestMethod.POST)
	public Result batchDelExecution(@RequestBody List<Execution> executions) {
	    User user= LoginUtils.getCurrentUserInfo();
        try{ 
            if(executions.size()<=0){
                return Result.error("execution-batchDel-data-err-0","请上送待删除数据列表");
            }
             List<Execution> datasDb=executionService.listByIds(executions.stream().map(i-> i.getId() ).collect(Collectors.toList()));

            List<Execution> can=new ArrayList<>();
            List<Execution> no=new ArrayList<>();
            for (Execution data : datasDb) {
                if(true){
                    can.add(data);
                }else{
                    no.add(data);
                } 
            }
            List<String> msgs=new ArrayList<>();
            if(can.size()>0){
                executionService.removeByIds(can);
                msgs.add(LangTips.transMsg("del-ok-num","成功删除%s条数据.",can.size()));
            }
    
            if(no.size()>0){ 
                msgs.add(LangTips.transMsg("not-allow-del-num","以下%s条数据不能删除:【%s】",no.size(),no.stream().map(i-> i.getId() ).collect(Collectors.joining(","))));
            }
            if(can.size()>0){
                 return Result.ok(msgs.stream().collect(Collectors.joining()));
            }else {
                return Result.error(msgs.stream().collect(Collectors.joining()));
            } 
        }catch (BizException e) { 
           return Result.error(e);
        }catch (Exception e) {
            return Result.error(e);
        }


	} 

	@ApiOperation( value = "act_ru_execution-根据主键查询一条数据",notes=" ")
     @ApiResponses({
            @ApiResponse(code = 200,response=Execution.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")
    })
    @RequestMapping(value="/queryById",method=RequestMethod.GET)
    public Result queryById(Execution execution) {
        Execution data = (Execution) executionService.getById(execution);
        return Result.ok().setData(data);
    }

}
